package br.com.tabletcaixa.serial;

import java.util.ArrayList;
import java.util.List;

import br.com.tabletcaixa.db.DBHelper;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class SerialDAO {

	private SQLiteDatabase db;
	private DBHelper dbHelper;
	
	private String[] colunas = {DBHelper.SERIAL_ID,
			DBHelper.SEIRAL_DESCRICAO};
	
	public SerialDAO(Context context){
		
		dbHelper = new DBHelper(context);
		
	}
	
	public void conectar(){
		
		db = dbHelper.getWritableDatabase();
		
	}
	
	public void desconectar(){
		
		dbHelper.close();
		
	}
	
	public long cadastrarSerial(SerialVO serial){
		
		try{
			
			ContentValues values = new ContentValues();
			values.put(DBHelper.SEIRAL_DESCRICAO, serial.getDescricao());
			
			return db.insert(DBHelper.TBL_SERIAL, null, values);
			
		}catch(Exception e){
			
			e.printStackTrace();
			e.getMessage();
			
		}
		
		return 0;
		
	}
	
	public List<SerialVO> buscarSerial(){
		
		List<SerialVO> lstSerial = new ArrayList<SerialVO>();
		
		Cursor cursor = db.query(DBHelper.TBL_SERIAL, colunas, 
				null, null, null, null, null);
		
		cursor.moveToFirst();
		
		while(!cursor.isAfterLast()){
			
			SerialVO lSerial = cursorToSerial(cursor);
			lstSerial.add(lSerial);
			cursor.moveToNext();
			
		}
		
		cursor.close();
		return lstSerial;
		
	}
	
	private SerialVO cursorToSerial(Cursor cursor){
		
		SerialVO serial = new SerialVO();
		serial.setId(cursor.getLong(0));
		serial.setDescricao(cursor.getString(1));
		
		return serial;
		
	}
	
}
